import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn import metrics

Aute_Data = pd.read_excel('将要聚类分析的数据.xlsx')

#分析价格price和发动机重量curb-weight的聚类图
data=[]
for i in range(len(Aute_Data)):
	data.append([Aute_Data['curb-weight'][i],Aute_Data['price'][i]])
#创建kmeans模型
col_dic = {0:'blue',1:'green',2:'orange',3:'gray',4:'magenta',5:'black'}
kmeans_2=KMeans(n_clusters=6,random_state=0)
assignments_km2=kmeans_2.fit_predict(data)
assign_color_km2 = [col_dic[x] for x in assignments_km2]

#画图分析curb-weight和price之间的关系
plt.subplot(1,2,1)
plt.scatter(Aute_Data['curb-weight'],Aute_Data['price'],c=assign_color_km2)
plt.xlabel('curb-weight')
plt.ylabel('price')


#分析价格price和city-mpg的聚类图
data=[]
for i in range(len(Aute_Data)):
	data.append([Aute_Data['city-mpg'][i],Aute_Data['price'][i]])
#创建kmeans模型
col_dic = {0:'blue',1:'green',2:'orange',3:'gray',4:'magenta',5:'black'}
kmeans_2=KMeans(n_clusters=6,random_state=0)
assignments_km2=kmeans_2.fit_predict(data)
assign_color_km2 = [col_dic[x] for x in assignments_km2]

#画图分析curb-weight和price之间的关系
plt.subplot(1,2,2)
plt.scatter(Aute_Data['city-mpg'],Aute_Data['price'],c=assign_color_km2)
plt.xlabel('city-mpg')
plt.ylabel('price')

#调整子图边距
plt.subplots_adjust(hspace=0.5,wspace=0.5)
plt.show()

#计算Calinski-Harabaz Index，类间距除以类内距，越大越好
score = metrics.calinski_harabasz_score(data,assign_color_km2)
print(score)





